const router = require("koa-router")();
const main = require("../models");
router.get("/login", async ctx => {
    await ctx.render("login")
})
router.get("/register", async ctx => {
    await ctx.render("register")
})
router.get("/home", async ctx => {
    ctx.body = "首页"
})
router.post("/doRegister", async ctx => {
    console.log(ctx.request.body);
    var { username, pwd } = ctx.request.body;
    var userCollection = await main("Member");
    var res = await userCollection.find({ username }).toArray();
    if (res.length) {
        ctx.body = "<script>alert('用户名已经被注册');location.href='/register'</script>"
    } else {

        var res = await userCollection.insertOne({ username, pwd });
        ctx.body = "<script>alert('注册成功,恭喜进入首页');location.href='/home'</script>"
    }
})
router.post("/doLogin", async ctx => {
    console.log(ctx.request.body);
    var { username, pwd } = ctx.request.body;
    var userCollection = await main("Member");
    var res = await userCollection.find({ username }).toArray();
    if (res.length) {
        await ctx.redirect("/home")
    } else {
        ctx.body = "<script>alert('用户名或密码错误');location.href='/login'</script>"
    }
})
module.exports = router